﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;

namespace KFGame
{
    [DisallowMultipleComponent]
    public class KFSeralPortToEvent : MonoBehaviour
    {
        /// <summary>
        /// 转换事件对象项
        /// </summary>
        struct EventConfigData
        {
            //原事件名称
            public string from;
            //转换成 KFEvent 的名字
            public string to;
            //事件分类
            public string type;
            //标签名
            public string tag;
        }

        //事件管理集
        Dictionary<string, EventConfigData> configs = new Dictionary<string, EventConfigData>();
        //运行配置 
        public static string eventrunPath = Application.streamingAssetsPath + "/KFConfig/kfseralporteventstofkevent.ini";



        KFEventManager kFEventManager;

        /// <summary>
        /// 初始化
        /// </summary>
        void Start()
        {
            loadConfog();

            foreach (var se in KFSeralPort.seralPorCs)
            {
                se.Value.addListener(onSeralPort);
            }

            kFEventManager = KFEventManager.Instantiation();
        }

        /// <summary>
        ///  接口回调
        /// </summary>
        /// <param name="fiter"></param>
        void onSeralPort(DataFiter fiter)
        {
            //  KF.Log("event to kfevent " + fiter.name);
            foreach (var item in configs)
            {
                if (item.Value.from == fiter.name)
                {
                    
                    EventConfigData data =item.Value;

                    KFEvent e = new KFEvent(data.to, data.type);
                    e.status = Convert.ToInt32(fiter.ischeck);
                    e.valueInt = 1;
                    e.tag = data.tag;

                    kFEventManager.Pop(e);
                }
            }

        }

        /// <summary>
        /// 关闭对象时
        /// </summary>
        public void close()
        {
            foreach (var se in KFSeralPort.seralPorCs)
                se.Value.removeListener(onSeralPort);

        }

        /// <summary>
        /// 加载配置 
        /// </summary>
        void loadConfog()
        {
              
            INIParser iNIParser = new INIParser();
            iNIParser.Open(eventrunPath);

            int a=0;
            foreach (var item in iNIParser.SectionNames())
            {
                EventConfigData data = new EventConfigData();
                data.from = iNIParser.ReadValue(item, "fromevent", "");
                data.to = iNIParser.ReadValue(item, "toevent", "KFE_NOEVENT");
                data.type = iNIParser.ReadValue(item, "type", "KFE_TYPE_DEFAULT");
                data.tag = iNIParser.ReadValue(item, "tag", "KFTAG");

                 a++;
                configs.Add("other:"+item+"-"+data.from+a , data);
            }
        }

    }
}
